package com.fjwt.gz.service.activity.platform.acte024;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fjwt.gz.core.cache.RedisUtil;
import com.fjwt.gz.core.constants.Constants;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.db.bo.ActivityUserTimesBO;
import com.fjwt.gz.db.dto.FansActivityDTO;
import com.fjwt.gz.db.entity.*;
import com.fjwt.gz.db.vo.ActivityAwardVO;
import com.fjwt.gz.service.activity.BaseActivityService;
import com.fjwt.gz.service.impl.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 	邀请助力活动------
 *
 */
@Slf4j
@Service
public class ACTE024Service extends BaseActivityService<Object> {

    private static String logPrefix = "【邀请助力活动】";
    @Autowired
    private ActivityAwardService activityAwardService;
    @Autowired
    private ActivityHelpService activityHelpService;
    @Autowired
    private ActivityShareService activityShareService;
    @Autowired
    private ActivitySettingService activitySettingService;
    @Autowired
    private FansAwardService fansAwardService;

    /**
     * 参与活动
     */
    @Override
    public ActivityAwardVO takePartIn(FansActivityDTO fansActivityDTO) {
        log.info("进入邀请助力活动");
        super.takePartIn(fansActivityDTO);
        Long fansId = fansActivityDTO.getFansId();
        Long activityId = fansActivityDTO.getActivityId();

        // 检测用户参与限制条件
        JSONObject jsonObject = activitySettingService.checkActivitySetting(fansEntity, fansActivityDTO.getAppId(), redisOutTime, activityEntity);

        // 检测活动奖品配置
        String activityAwardKey = String.format("%s%s:%s", Constants.REDIS_ACTIVITY.FILENAME, activityId, Constants.REDIS_ACTIVITY.AWARD);
        log.info("检测活动奖品配置redisKey:{}", activityAwardKey);
        List<ActivityAwardEntity> activityAwardList = RedisUtil.getObject(activityAwardKey, new com.alibaba.fastjson2.TypeReference<List<ActivityAwardEntity>>() {
        });
        log.info("检测活动奖品配置redisValue:{}", JSONUtil.toJsonStr(activityAwardList));

        if (activityAwardList == null) {
            LambdaQueryWrapper<ActivityAwardEntity> activityAwardWrapper = new LambdaQueryWrapper<>();
            activityAwardWrapper.eq(ActivityAwardEntity::getActivityId, activityId);
            activityAwardList = activityAwardService.list(activityAwardWrapper);
            log.info("检测活动奖品配置redisValue为空，拉取活动卡券信息:{}", JSONUtil.toJsonStr(activityAwardList));
            if (activityAwardList != null && !activityAwardList.isEmpty()) {
                log.info("检测活动奖品配置放到redis中的信息，redisKey:{},redisValue:{},redisOutTime:{},TimeUnit:{}", activityAwardKey, JSONUtil.toJsonStr(activityAwardList), redisOutTime, "TimeUnit.MILLISECONDS");
                RedisUtil.set(activityAwardKey, activityAwardList, redisOutTime, TimeUnit.MILLISECONDS);
            }
        } else {
            log.info(String.format("活动奖品配置表在Redis中存在，ID: %s", activityId));
        }

        // 校验活动分享限制
        String activityShareKey = String.format("%s%s:%s", Constants.REDIS_ACTIVITY.FILENAME, activityId, Constants.REDIS_ACTIVITY.SHARE);
        log.info("活动分享限制条件redisKey:{}", activityShareKey);
        ActivityShareEntity activityShareEntity = RedisUtil.getObject(activityShareKey, ActivityShareEntity.class);
        if (activityShareEntity == null) {
            activityShareEntity = activityShareService.getOne(ActivityShareEntity.gw().eq(ActivityShareEntity::getActivityId, activityId));
            if (activityShareEntity != null) {
                RedisUtil.set(activityShareKey, activityShareEntity, redisOutTime, TimeUnit.MILLISECONDS);
                log.info("用户参与限制条件，从数据库加载到redis缓存中，redisKey:{},redisValue:{},redisExpireTime:{},TimeUnit:{}", activityShareKey, JSONUtil.toJsonStr(activityShareEntity), redisOutTime, "TimeUnit.MILLISECONDS");
            }else {
                throw new BizException("分享活动配置有误");
            }
        } else {
            log.info("用户参与限制条件，redis缓存，redisKey:{},redisValue:{},redisExpireTime:{},TimeUnit:{}", activityShareKey, JSONUtil.toJsonStr(activityShareEntity), redisOutTime, "TimeUnit.MILLISECONDS");
        }

        DateTime date = DateUtil.date();
        LambdaQueryWrapper<ActivityHelpEntity> gw = ActivityHelpEntity.gw().eq(ActivityHelpEntity::getFansId, fansId)
                .eq(ActivityHelpEntity::getActivityId,activityId);
        if (activityShareEntity.getShareMaxNum() == 1) {
            // 查询参与记录
            List<ActivityHelpEntity> activityHelpList = activityHelpService.list(gw);
            if (ObjectUtils.isNotEmpty(activityHelpList)) {
                throw new BizException("您已参与过该活动");
            }
        } else if (activityShareEntity.getShareMaxNum() > 1) {
            if (activityShareEntity.getSharePeriodType() > 0) {
                if (activityShareEntity.getSharePeriodType() == 1) {
                    gw.between(ActivityHelpEntity::getCreatedAt, DateUtil.beginOfDay(date), DateUtil.endOfDay(date));
                }else if (activityShareEntity.getSharePeriodType() == 2) {
                    gw.between(ActivityHelpEntity::getCreatedAt, DateUtil.beginOfWeek(date), DateUtil.endOfWeek(date));
                }else if (activityShareEntity.getSharePeriodType() == 3) {
                    gw.between(ActivityHelpEntity::getCreatedAt, DateUtil.beginOfMonth(date), DateUtil.endOfMonth(date));
                }
                long count = activityHelpService.count(gw);
                if (count >= activityShareEntity.getSharePeriodTimes()) {
                    String type = activityShareEntity.getSharePeriodType() == Constants.PERIOD.DAY ? "日" : activityShareEntity.getSharePeriodType() == Constants.PERIOD.WEEK ? "周" : activityShareEntity.getSharePeriodType() == Constants.PERIOD.MONTH ? "月" : "年";
                    throw new BizException(String.format("对不起，您每%s参与的次数已用完", type));
                }
            }
        }


        // 参与活动
        ActivityHelpEntity fActivityHelp = new ActivityHelpEntity();
        fActivityHelp.setActivityId(activityId);
        fActivityHelp.setFansId(fansId);
        fActivityHelp.setSuccessStandardNum(0);
        fActivityHelp.setTotalHelpNum(0);
        fActivityHelp.setSurplusSuccessNum(0);
        fActivityHelp.setAppId(fansActivityDTO.getAppId());
        fActivityHelp.setUpdatedAt(date);
        fActivityHelp.setCreatedAt(date);
        activityHelpService.save(fActivityHelp);

        //更新Redis中参与的次数
        ActivityUserTimesBO activityUserTimesBO = jsonObject.getObject("activityUserTimesBO", ActivityUserTimesBO.class);
        if (ObjectUtils.isNotEmpty(activityUserTimesBO)){
            activitySettingService.updateRedisParticipateNum(jsonObject.getString("currentTimesKey"), activityUserTimesBO, redisOutTime);
        }
        Boolean userJoinScoreValue = jsonObject.getObject("userJoinScoreValue", Boolean.class);
        if (ObjectUtils.isNotEmpty(userJoinScoreValue)){
            RedisUtil.set(jsonObject.getString("userJoinScoreKey"), userJoinScoreValue, redisOutTime, TimeUnit.MILLISECONDS);
        }

        return null;
    }
}
